//
// Created by Mengyu Li on 2021/3/10.
//

import Foundation
import LMDB

public class StoreContainer {
    let path: String
    private let environment: Environment

    private var stores = [String: Store]()

    public init(path: String, maxStoreCount: UInt32 = 32) throws {
        self.path = path
        environment = try Environment(path: path, maxDBs: maxStoreCount)
    }
}

public extension StoreContainer {
    subscript(name: String) -> Store {
        switch stores[name] {
        case .none:
            do {
                let store = try Store(name: name, environment: environment)
                stores[name] = store
                return store
            } catch { fatalError("\(error)") }
        case .some(let store):
            return store
        }
    }
}

public extension StoreContainer {
    var storeCount: Int {
        stores.count
    }
}
